package com.xmg.threadpool;

import lombok.extern.slf4j.Slf4j;

import java.time.*;
import java.util.concurrent.*;

@Slf4j(topic = "p.TestTimer")
public class ScheduledTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
//
//        System.out.println(LocalTime.now());
//        pool.scheduleAtFixedRate(()->{
//            log.info("running.....");
//        },1,1,TimeUnit.SECONDS);
//
//        pool.scheduleWithFixedDelay(()->{
//            log.info("running.....");
//        },1,1,TimeUnit.SECONDS);

//        ExecutorService pool1 = Executors.newFixedThreadPool(1);
//        Future<Boolean> task1 = pool1.submit(() -> {
//            log.info("task1");
//            int x = 1 / 0;
//            return true;
//        });
//        log.debug("result:{}",task1.get());

//        pool.shutdown();
        //每周四定时执行
        long period = 1000 * 60 * 60 * 24 * 7;
        LocalDateTime now = LocalDateTime.now();
        //找周四时间,下面方法找出的是本周四，如果当前时间超过周四会有问题
        LocalDateTime time = now.withHour(18).withMinute(0).withSecond(0).withNano(0).with(DayOfWeek.THURSDAY);
        //如果当前时间大于周四，找到下个周四
        if(now.compareTo(time)>0){
            time.plusWeeks(1);
        }
        System.out.println(time);

        long initailDelay = Duration.between(now, time).toMillis();
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);

        pool.scheduleAtFixedRate(()->{
            log.info("每周四18点执行这个任务");
        },initailDelay,period,TimeUnit.MILLISECONDS);
    }

    private static void delay(ScheduledExecutorService pool) {
        pool.schedule(()->{
            log.info("task1");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },1, TimeUnit.SECONDS);


        pool.schedule(()->{
            log.info("task2");
        },1, TimeUnit.SECONDS);
    }
}
